#!/bin/bash

IMAGE_NAME=vdisk.img
IMAGE_PATH=out/bxImage

if [ ! -d ${IMAGE_PATH} ]; then
    mkdir -p ${IMAGE_PATH}
fi

if [ -f ${IMAGE_PATH}/${IMAGE_NAME} ]; then
    rm -f ${IMAGE_PATH}/${IMAGE_NAME}
fi

IMAGE_SIZE=32768 # 32G
BLOCK_SIZE=1M  # 1 MB
# Create the actual disk image - 128MB
dd if=/dev/zero of=${IMAGE_PATH}/${IMAGE_NAME} count=${IMAGE_SIZE} bs=${BLOCK_SIZE}
 
# Make the partition table, partition and set it bootable.
parted -s ${IMAGE_PATH}/${IMAGE_NAME} mklabel msdos mkpart primary ext2 1M ${IMAGE_SIZE}M set 1 boot on
 
# Map the partitions from the image file
PRIME_PART=`sudo kpartx -av ${IMAGE_PATH}/${IMAGE_NAME}`
PRIME_PART=${PRIME_PART% (*}
PRIME_PART=${PRIME_PART:8}
# sleep a sec, wait for kpartx to create the device nodes
sleep 1
 
# Make an ext4 filesystem on the first partition.
sudo mkfs.ext4 /dev/mapper/${PRIME_PART}
 
# Mount the filesystem via loopback
sudo mount /dev/mapper/${PRIME_PART} /mnt

sudo grub-install --no-floppy                                                    \
              --root-directory=/mnt                                              \
              /dev/${PRIME_PART:0:`expr ${#PRIME_PART}-2`}

sudo cp ./configs/grub.cfg /mnt/boot/grub/grub.cfg
sudo cp ./external/kernel/linux/linux-6.1/arch/x86_64/boot/bzImage /mnt/boot/vmlinuz-6.1.0
sudo cp ./external/kernel/linux/linux-6.1/vmlinux.map /mnt/boot/System.map-6.1.0
sudo cp /boot/initrd.img-5.19.0-46-generic /mnt/boot/initrd.img-6.1.0

# # Unmount the loopback
sudo umount /mnt
 
# # Unmap the image
sudo kpartx -d ${IMAGE_PATH}/${IMAGE_NAME}